<template>
  <div>
    <van-dialog v-model="showDialog" title="开启评价" show-cancel-button :before-close="onBeforeClose">
      <van-form ref="dataForm" @submit="onSubmit" label-width="1.8rem" :show-error="false">
        <van-field
          readonly
          clickable
          name="timeData"
          required
          :value="formData.timeData"
          label="评价时间"
          placeholder="请选择"
          @click="showPicker = true"
          :rules="[{ required: true, message: '请选择评价时间' }]"
          right-icon="arrow" />
      </van-form>
    </van-dialog>
    <!-- <van-popup v-model="showPopup" round :close-on-click-overlay="false" class="popup">
      <div class="popup-title">开启评价</div>
      <van-form @submit="onSubmit" label-width="1.8rem" :show-error="false">
        <van-field
          readonly
          clickable
          name="timeData"
          required
          :value="formData.timeData"
          label="评价时间"
          placeholder="请选择"
          @click="showPicker = true"
          :rules="[{ required: true, message: '请选择评价时间' }]"
          right-icon="arrow"
        />
        <div class="btn-group">
          <van-button block plain hairline native-type="button" @click="onCancel">取 消</van-button>
          <van-button block plain hairline native-type="submit">保 存</van-button>
        </div>
      </van-form>
    </van-popup> -->

    <van-popup v-model="showPicker" position="bottom">
      <van-picker
        show-toolbar
        title="时间选择"
        :columns="timeList"
        value-key="name"
        @confirm="onConfirm"
        @cancel="showPicker = false" />
    </van-popup>
  </div>
</template>
<script>
import moment from 'moment'

import { startCycleEvaluation, getTaskAssessmentCycle } from '@api/api-task.js'
import { distinct } from '../../../common/filters'

moment.locale('zh-cn')

export default {
  name: 'OpenEvaluate',
  components: {},
  props: {
    /* 显示popup */
    showPopup: {
      type: Boolean,
      default: false,
      require: true,
    },
    /* 任务详情 */
    detailsData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      showDialog: false,
      assessmentType: '', // 考核周期
      showPicker: false,
      formData: {
        timeData: '',
        month: '', // 月
        quarter: '', // 季
        year: '', // 年
        taskId: '',
      },
      timeList: [
        {
          name: '2023',
          year: '2023',
          month: '01',
          quarter: '3',
        },
      ],
    }
  },
  computed: {},
  watch: {
    showPopup(newVal) {
      if (newVal) {
        this.showDialog = newVal
        this.getTaskAssessmentType()
      }
    },
  },
  created() {},
  mounted() {
    // this.columns = this.getdifflist(assignedTime.substr(0, 7), completeTime.substr(0, 7), 'months')
  },
  methods: {
    /* 获取任务考核类型 */
    async getTaskAssessmentType() {
      const { data } = await getTaskAssessmentCycle({ id: this.detailsData.id })
      this.assessmentType = data
      this.getChooseTime()
    },
    /* 获取可选的时间 */
    getChooseTime() {
      const { assignedTime = '', completeTime = '' } = this.detailsData
      if (this.assessmentType === 'ASSESSMENT_CYCLE_3') {
        // 年度考核
        // 默认展示当前年，如果当前年大于任务完成时限，按照任务完成时限的最大值
        if (new Date().getFullYear() <= new Date(completeTime).getFullYear()) {
          this.formData.year = String(new Date().getFullYear())
        } else {
          this.formData.year = String(new Date(completeTime).getFullYear())
        }
        // this.formData.year = String(new Date().getFullYear())
        this.formData.timeData = this.formData.year
        const yearArr = this.getdifflist(assignedTime.substr(0, 4), completeTime.substr(0, 4), 'years')
        this.dealPickerTime(yearArr, 'year')
      } else if (this.assessmentType === 'ASSESSMENT_CYCLE_2') {
        // 季度考核
        const timeArr = this.getdifflist(assignedTime.substr(0, 7), completeTime.substr(0, 7), 'months')
        // console.log(timeArr)
        const quarterArr = timeArr.map(item => {
          return `${item.substr(0, 4)}-${this.whitchQuarter(Number(item.split('-')[1]))}`
        })
        this.dealPickerTime(distinct(quarterArr, []), 'quarter')
      } else if (this.assessmentType === 'ASSESSMENT_CYCLE_1') {
        // 月度考核
        const monthArr = this.getdifflist(assignedTime.substr(0, 7), completeTime.substr(0, 7), 'months')
        this.dealPickerTime(monthArr, 'month')
      }
    },
    /* 处理弹出框的数据 */
    dealPickerTime(arr, type) {
      const timeList = arr.map(item => {
        const obj = {
          type: type,
          name: item,
          year: '',
          month: '',
          quarter: '',
        }
        if (type === 'year') {
          obj.year = item
        } else if (type === 'quarter') {
          obj.name = `${item.split('-')[0]}年第${item.split('-')[1]}季度`
          obj.year = item.split('-')[0]
          obj.quarter = item.split('-')[1]
        } else if (type === 'month') {
          obj.year = item.split('-')[0]
          obj.month = item.split('-')[1]
        }
        return obj
      })
      this.timeList = timeList
    },
    /* 点击弹窗确定按钮 */
    onBeforeClose(action, done) {
      // 点击了确定按钮
      if (action === 'confirm') {
        this.$refs.dataForm.validate(['timeData']).then(() => {
          this.onSubmit()
        })
        return done(false) // 直接return它即可阻止
      } else {
        // 点击了取消按钮
        this.onCancel()
        done(true) // 关闭弹窗, true可以省略
      }
    },
    /* 保存数据 */
    onSubmit() {
      this.formData.taskId = this.detailsData.id
      // console.log(this.formData)
      startCycleEvaluation({
        ...this.formData,
      }).then(res => {
        const { code = 0, msg = '' } = res
        if (code === 0) {
          this.onCancel()
          this.$toast.success(msg)
          this.$emit('success')
        }
      })
    },
    /* 关闭弹框 */
    onCancel() {
      this.showDialog = false
      this.$emit('cancel')
    },
    /* 获取俩个时间之间的所有时间 */
    getdifflist(startTime, endTime, type) {
      // type 为 days(天) , months(月), years(年)
      const dateArray = [] // dateArray 起止日期中间的所有日期列表
      let currentDate = moment(startTime) // 起止日期
      const stopDate = moment(endTime) // 截止日期
      // 开始日期小于等于结束日期,并循环
      while (currentDate <= stopDate) {
        if (type === 'days') {
          dateArray.push(moment(currentDate).format('YYYY-MM-DD')) // 两个日期间的所有日期
        } else if (type === 'months') {
          dateArray.push(moment(currentDate).format('YYYY-MM')) // 两个月份间的所有月份
        } else if (type === 'years') {
          dateArray.push(moment(currentDate).format('YYYY')) // 两个年份间的所有年份
        }
        currentDate = moment(currentDate).add(1, type) // 根据类型+1
      }
      return dateArray
    },
    /* 弹框确定操作 */
    onConfirm(val) {
      const { year = '', month = '', quarter = '', type = '', name = '' } = val
      switch (type) {
        case 'year':
          break
        case 'quarter':
          this.formData.quarter = quarter
          break
        case 'month':
          this.formData.month = month
          break

        default:
          break
      }
      this.formData.year = year
      this.formData.timeData = name
      this.showPicker = false
    },
    /* 根据输入的月份判断是哪一个季节 */
    whitchQuarter(month) {
      let quarter = ''
      month = Number(month)
      switch (month) {
        case 1:
        case 2:
        case 3:
          quarter = '1'
          break
        case 4:
        case 5:
        case 6:
          quarter = '2'
          break
        case 7:
        case 8:
        case 9:
          quarter = '3'
          break
        case 10:
        case 11:
        case 12:
          quarter = '4'
          break
        default:
          console.error('The entered time is incorrect')
      }
      return quarter
    },
  },
}
</script>
<style lang="scss" scoped>
.popup {
  width: px2rem(690);
  // padding: px2rem(32);
}
.van-cell {
  padding: 10px 16px;
}
.popup-title {
  text-align: center;
  font-size: $fontSize32;
  padding: px2rem(32) 0;
  border-bottom: 1px solid #eee;
}
.btn-group {
  display: flex;
}
.van-radio--horizontal {
  margin-right: 12px;
}
</style>
